package com.qf.xiaomi.dao.impl;

import com.qf.xiaomi.dao.userDao;
import com.qf.xiaomi.pojo.TbUser;
import com.qf.xiaomi.utils.DButils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;
import java.util.Date;

public class userDaoImpl implements userDao {
    QueryRunner queryRunner = new QueryRunner(DButils.getdataSource());
    @Override
    public int add(TbUser user) {
        String sql="INSERT INTO `tb_user` ( `username`, `password`, `email`, `gender`, `code`) VALUES (?,?,?,?,?);";
        try {
            int update = queryRunner.update(sql,user.getUsername(),user.getPassword(),user.getEmail(),user.getGender(),user.getCode());
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public boolean selectUid(int id) {
        String sql="select * from tb_user where id=?;";
        try {
            TbUser query = queryRunner.query(sql, new BeanHandler<TbUser>(TbUser.class),id);
            if (query==null){
                return false;
            }else{
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }



    @Override
    public TbUser login(String username) {
        String sql="select * from tb_user where username=?";
        TbUser user = null;
        try {
            user = queryRunner.query(sql, new BeanHandler<TbUser>(TbUser.class), username);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int updateLoginTime(long id) {
        String sql = "update tb_user set lastlogintime=currentlogintime ,currentlogintime=? where id=?";
        try {
            int count = queryRunner.update(sql, new Date(), id);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public TbUser IsAdmin(String username) {
        String sql ="select * from tb_user where username=?";
        TbUser tbUser = null;
        try {
            tbUser = queryRunner.query(sql, new BeanHandler<>(TbUser.class), username);

            return tbUser;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
